package ca.demo.databasedemo;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;
import android.widget.TextView;

/*
 * Steps to using the DB:
 * 1. [DONE] Instantiate the DB Adapter
 * 2. [DONE] Open the DB
 * 3. [DONE] use get, insert, delete, .. to change data.
 * 4. [DONE]Close the DB
 */

/**
 * Demo application to show how to use the 
 * built-in SQL lite database.
 */
public class MainActivity extends Activity {
	
	private ProgressDialog pDialog;
	private static String url = "http://192.168.1.137/karaoke-All.php";
	DBAdapter myDb;
	
	private static final String TAG_CONTACTS = "song";
	private static final String TAG_ID = "id";
	private static final String TAG_NAME = "title";
	private static final String TAG_EMAIL = "title_simple";
	private static final String TAG_ADDRESS = "lang	";
	private static final String TAG_GENDER = "lyric";
	
	// contacts JSONArray
	JSONArray lienlac = null;
	// Hashmap for ListView
		ArrayList<HashMap<String, String>> contactList;
		
		
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		contactList = new ArrayList<HashMap<String, String>>();

		openDB();
		
		// Calling async task to get json
				new GetContacts().execute();
	}
	@Override
	protected void onDestroy() {
		super.onDestroy();	
		closeDB();
	}


	private void openDB() {
		myDb = new DBAdapter(this);
		myDb.open();
	}
	private void closeDB() {
		myDb.close();
	}

	
	
	private void displayText(String message) {
        TextView textView = (TextView) findViewById(R.id.textDisplay);
        textView.setText(message);
	}
	
	

	
	/*------------------------------------------------------------------------
/*Joson to begin*/

	/**
	 * Async task class to get json by making HTTP call
	 * */
	private class GetContacts extends AsyncTask<Void, Void, Void> {

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			// Showing progress dialog
			pDialog = new ProgressDialog(MainActivity.this);
			pDialog.setMessage("Please wait...");
			pDialog.setCancelable(false);
			pDialog.show();

		}

		@Override
		protected Void doInBackground(Void... arg0) {
			// Creating service handler class instance
			ServiceHandler sh = new ServiceHandler();

			// Making a request to url and getting response
			String jsonStr = sh.makeServiceCall(url, ServiceHandler.POST);

			Log.d("Response: ", "> " + jsonStr);
		
			if (jsonStr != null) {
				try {
					JSONObject jsonObj = new JSONObject(jsonStr);
					
					// Getting JSON Array node
					lienlac = jsonObj.getJSONArray(TAG_CONTACTS);
					Log.d("Do dai chuoi: ", " " + lienlac.length());
					// looping through All Contacts
				
					for (int i = 0; i < lienlac.length(); i++) {
						JSONObject c = lienlac.getJSONObject(i);
						Log.d("Giá trị : ", " " + i);
						String id = c.getString(TAG_ID);
						String name = c.getString(TAG_NAME);
						String email = c.getString(TAG_GENDER);
					//	String address = c.getString(TAG_ADDRESS);
						//String gender = c.getString(TAG_GENDER);// gioi tinh

					
						//long newId = 
						myDb.insertRow(id, name, email);
					//	Cursor cursor = myDb.getRow(newId);
						//displayRecordSet(cursor);
						
					
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			} else {
				Log.e("ServiceHandler", "Couldn't get any data from the url");
			}

			return null;
		}
		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			// Dismiss the progress dialog
			if (pDialog.isShowing())
				pDialog.dismiss();
			/**
			 * Updating parsed JSON data into SQlite
			 * */
			

		
		}
	
		

	}
	
	// Json to end
	//-------------------------------------------------------------------------
	
	public void onClick_AddRecord(View v) {
		displayText("Clicked add record!");
	
		long newId = myDb.insertRow("Jenny", "5559", "Green");
		
		// Query for the record we just added.
		// Use the ID:
		Cursor cursor = myDb.getRow(newId);
		displayRecordSet(cursor);
		
	}
	
	public void onClick_ClearAll(View v) {
		displayText("Clicked clear all!");
		myDb.deleteAll();
	}

	public void onClick_DisplayRecords(View v) {
		displayText("Clicked display record!");
		Cursor cursor = myDb.getAllRows();
		//Cursor cursor = myDb.getRow();
		displayRecordSet(cursor);
	
		
		
		
	}
	
	// Display an entire recordset to the screen.
	private void displayRecordSet(Cursor cursor) {
		String message = "";
		// populate the message from the cursor
		
		// Reset cursor to start, checking to see if there's data:
		if (cursor.moveToFirst()) {
			do {
				// Process the data:
				int id = cursor.getInt(DBAdapter.COL_ROWID);
				String name = cursor.getString(DBAdapter.COL_NAME);
				int studentNumber = cursor.getInt(DBAdapter.COL_STUDENTNUM);
				String favColour = cursor.getString(DBAdapter.COL_FAVCOLOUR);
				
				// Append data to the message:
				message += "id=" + id
						   +", name=" + name
						   +", #=" + studentNumber
						   +", Colour=" + favColour
						   +"\n";
			} while(cursor.moveToNext());
		}
		
		// Close the cursor to avoid a resource leak.
		cursor.close();
		
		displayText(message);
	}
}










